<script lang="ts" setup>
import { apiUserAdd, apiUserDisable, apiUserList } from "@/api/interface"
import del from "@/assets/docs/del.svg"
// import edit from "@/assets/docs/edit.svg"
import IntegralModel from "@/components/Create/components/integralModel.vue"
import { usePagination } from "@/hooks/usePagination"
import dayjs from "dayjs"
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus"
import _ from "lodash"
import Pubsub from "pubsub-js"
import { onMounted, reactive, ref, watch } from "vue"

defineOptions({
  // 命名当前组件
  name: "Administrators"
})

const pid = ref("")

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const isIntegral = ref<boolean>(false)
const editData = ref({})

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  nickname: "",
  mobile_numb: "",
  score: ""
})

const rulesPhone = (rules: any, value: any, callback: any) => {
  if (!/^1[3456789]\d{9}$/.test(value)) {
    callback("手机号信息有误")
  } else {
    callback()
  }
}
const formRules: FormRules = reactive({
  nickname: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  mobile_numb: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur"
    },
    {
      validator: rulesPhone,
      trigger: "blur",
      message: "请输入正确手机号"
    }
  ]
})

const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      apiUserAdd(formData)
        .then(() => {
          ElMessage.success("新增成功")
          getTableData()
        })
        .finally(() => {
          dialogVisible.value = false
        })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
const resetForm = () => {
  formData.nickname = ""
  formData.mobile_numb = ""
}
//#endregion

//#region 删
const handleDelete = async (row: any) => {
  const confirm = await ElMessageBox.confirm(`正在删除用户：${row.nickname}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
  if (confirm === "confirm") {
    await apiUserDisable({ id: row.id })
    // tableData.value = tableData.value.filter(item => item.id !== row.id)
    getTableData()

    ElMessage.success("删除成功")
  } else {
    ElMessage.error("删除失败，请稍后重试")
  }
}
//#endregion

//#region
const tableData = ref<any[]>([])
const searchData = reactive({
  nickname: "",
  mobile: ""
})
const getTableData = () => {
  loading.value = true
  const parame = {
    page: paginationData.currentPage,
    mobile: searchData.mobile,
    nickname: searchData.nickname
  }
  apiUserList(parame)
    .then((res) => {
      paginationData.total = res.data.count
      tableData.value = res.data.list.map((e: any) => {
        e.createtime = dayjs.unix(e.createtime).format("YYYY-MM-DD  HH:mm:ss")
        return e
      })
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  console.log(searchData)
  getTableData()
  // paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
  const newList = tableData.value.filter((item) => {
    return item.mobile.includes(searchData.mobile)
  })
  tableData.value = newList
  console.log(newList)
}
const resetSearch = () => {
  // searchFormRef.value?.resetFields()
  searchData.mobile = ""
  searchData.nickname = ""
  handleSearch()
}
//#endregion

// 积分编辑
const onEdit = (e: any) => {
  // 深拷贝
  const newData = _.cloneDeep(e)
  // 编辑传入参数
  editData.value = newData
  // 打开编辑
  isIntegral.value = true
}

// 积分编辑回显
const editDpData = () => {
  // 只更新列表
  getTableData()
  // 关闭编辑
  isIntegral.value = false
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

onMounted(() => {
  //消息订阅
  pid.value = Pubsub.subscribe("ADMINISTRATORS_DIALOG", () => (dialogVisible.value = true))
})
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="searchData.nickname" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="mobile_numb" label="手机号">
          <el-input v-model="searchData.mobile" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card defaultTable">
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="id" />
        <el-table-column prop="nickname" label="用户名" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="score" label="token积分数量" />
        <el-table-column prop="t_image" label="AI·生图" />
        <el-table-column prop="t_voice" label="AI·语音" />
        <el-table-column prop="t_chat" label="AI·对话次数" />

        <el-table-column prop="createtime" label="创建时间" />
        <el-table-column align="right" label="操作" width="150">
          <template #default="scope">
            <div class="dflex justify-content-end">
              <div class="base-edit" @click="onEdit(scope.row)">
                <i class="iconfont icon-jifen" style="font-size: 20px; color: #999" />
              </div>
              <div class="base-del" @click="handleDelete(scope.row)">
                <img :src="del" alt="" srcset="" />
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="justify-content-end p10_0"
        :layout="paginationData.layout"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :currentPage="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 新增管理员 -->
    <el-dialog
      class="dialogAdapter"
      style="border-radius: 10px"
      v-model="dialogVisible"
      title="新增管理员"
      @close="resetForm"
    >
      <el-form label-position="top" ref="formRef" :model="formData" :rules="formRules" label-width="110px">
        <el-form-item prop="nickname" label="用户名">
          <el-input v-model="formData.nickname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="mobile_numb" label="手机号">
          <el-input v-model="formData.mobile_numb" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item prop="score" label="token积分数量">
          <el-input v-model="formData.score" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>

    <!-- 积分设置 -->
    <IntegralModel
      v-if="isIntegral"
      :visible="isIntegral"
      type="edit"
      :editData="editData"
      @close="isIntegral = false"
      @editDpData="editDpData"
    />
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.el-card {
  box-shadow: none;
  border: none;

  .base-edit {
    margin-right: 20px;
    cursor: pointer;
  }

  .base-del {
    img {
      margin-top: 2px;
    }
  }
}
</style>
